$(function () {
  const { emailOk, emailError, emailInfo } = {
    emailOk: "邮箱格式正确！",
    emailError: "邮箱格式错误",
    emailInfo: "请输入正确的邮箱",
  };

  const { loginOk, loginError } = {
    loginOk: "登录成功",
    loginError: "登录失败",
  };

  const { registerOk, registerError } = {
    registerOk: "注册成功",
    registerError: "注册失败",
  };

  // 正则 邮箱格式
  const [reg] = [/^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/];

  //点击登录
  $(".dl").click(function () {
    loadShow();
    let [aaa, bbb] = [$(".aaa").val(), $(".bbb").val()];
    if (isEmpty(aaa)) {
      if (reg.test(aaa)) {
        getAjax();
      } else {
        lodaHide();
        topInfo(emailError, emailInfo);
      }
    } else {
      lodaHide();
      topInfo("内容为空", "请输入内容");
    }
  });

  // 判断是否为空
  function isEmpty(str) {
    if (str != null && str != "") {
      return true;
    }
    if (str == null && str == "") {
      return false;
    }
  }

  // 调用接口 ajax
  function getAjax() {
    $.ajax({
      type: "GET",
      url: "http://192.168.43.8:8081/login",
      data: { account: $(".aaa").val(), pwd: $(".bbb").val() },
      success: function (res) {
        lodaHide();
        if (res.status == 1) {
          console.log(res.name);
          let n = res.name;
          sessionStorage.setItem("name",n);
          $(".aaa").val("");
          $(".bbb").val("");
          topInfo(loginOk, "3 秒后跳转首页");
          timerHref("./index.html", 3000);
        } else if (res.status == 0) {
          topInfo(loginError, "请注册或检查账户或密码");
        } else {
          topInfo(loginError, "请注册或检查账户或密码");
        }
      },
    });
  }

  //延时跳转页面
  function timerHref(location, delay) {
    setTimeout(function () {
      window.location.href = location;
    }, delay);
  }

  // 加载动画开启 关闭
  function loadShow() {
    $(".toy-train").show();
  }
  function lodaHide() {
    $(".toy-train").hide();
  }

  // 提示框
  function topInfo(title, message) {
    iziToast.show({
      class: "test",
      color: "dark",
      icon: "icon-contacts",
      title: title,
      message: message,
      position: "topCenter",
      transitionIn: "flipInX",
      transitionOut: "flipOutX",
      progressBarColor: "rgb(0, 255, 184)",
      image: "img/avatar.jpg",
      imageWidth: 70,
      timeout: 2500,
      layout: 2,
      onClose: function () {
        console.info("onClose");
      },
      iconColor: "rgb(0, 255, 184)",
    });
  }
});
